////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010 Gabriel Montagné Láscaris-Comneno and Alberto
//  Brealey-Guzmán.
//
//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the "Software"),
//  to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense,
//  and/or sell copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
//  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

package com.rojored.net
{

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.rpc.IResponder;

/**
 *  Handles the downloading and interpretation of bitmap assets.
 *
 *  @author gabriel montagné láscaris-comneno gabriel@rojored.com
 */
public class BitmapAssetDownloader extends EventDispatcher
{

    //--------------------------------------------------------------------------
    //
    //  Class constants
    //
    //--------------------------------------------------------------------------

    /**
     *  @private
     */
    private static const LOG:ILogger =
        Log.getLogger(getQualifiedClassName(BitmapAssetDownloader).replace(/\W+/g,
            "."));

    //--------------------------------------------------------------------------
    //
    //  Constructor
    //
    //--------------------------------------------------------------------------

    /**
     *  Constructor
     */
    public function BitmapAssetDownloader()
    {
        super();
    }

    //--------------------------------------------------------------------------
    //
    //  Variables
    //
    //--------------------------------------------------------------------------

    /**
     *  @private
     */
    private var urlLoader:URLLoader;

    /**
     *  @private
     */
    private var loader:Loader;

    /**
     *  @private
     */
    private var responder:IResponder;

    //--------------------------------------------------------------------------
    //
    //  Properties
    //
    //--------------------------------------------------------------------------

    //--------------------------------------
    //  bitmapData
    //--------------------------------------

    /**
     *  @private
     *  Storage for the bitmapData property
     */
    private var _bitmapData:BitmapData;

    [Bindable("bitmapDataChanged")]

    /**
     *  Loaded bitmap data.
     */
    public function get bitmapData():BitmapData
    {
        return _bitmapData;
    }

    /**
     *  @private
     */
    private function setBitmapData(value:BitmapData):void
    {
        if (_bitmapData == value)
            return;

        _bitmapData = value;
        dispatchEvent(new Event("bitmapDataChanged"));
    }

    //--------------------------------------
    //  useNoCacheHeader
    //--------------------------------------

    /**
     *  If <code>true</code> a <code>no-cache</code> header will be packed on
     *  the request.
     */
    public var useNoCacheHeader:Boolean;

    //--------------------------------------
    // isLoading
    //--------------------------------------

    /**
     *  @private
     *  Storage for the isLoading property
     */
    private var _isLoading:Boolean;

    [Bindable("isLoadingChanged")]

    /**
     *  If <code>true</code> an asset is being downloaded.
     */
    public function get isLoading():Boolean
    {
        return _isLoading;
    }

    /**
     *  @private
     */
    private function setIsLoading(value:Boolean):void
    {
        if (_isLoading == value)
            return;

        _isLoading = value;
        dispatchEvent(new Event("isLoadingChanged"));
    }

    //--------------------------------------------------------------------------
    //
    //  Methods
    //
    //--------------------------------------------------------------------------

    /**
     *  Initializes the download of an asset from a url.
     */
    public function loadAsset(source:String, responder:IResponder = null):void
    {
        this.responder = responder;
        if (!urlLoader)
        {
            urlLoader = new URLLoader();
            urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
            urlLoader.addEventListener(Event.COMPLETE, urlLoader_completeHandler);
            urlLoader.addEventListener(IOErrorEvent.IO_ERROR,
                urlLoader_ioErrorEventHandler);
        }

        var request:URLRequest = new URLRequest(source);
        if (useNoCacheHeader)
            request.requestHeaders.push(new URLRequestHeader("pragma",
                "no-cache"));

        setIsLoading(true);
        urlLoader.load(request);
    }

    /**
     *  Cancel the the current load process.
     */
    public function cancel():void
    {
        LOG.debug("cancel {0}", isLoading);
        if (isLoading)
            urlLoader.close();

        setIsLoading(false);
    }

    /**
     *  @private
     */
    private function parseBitmapData(stream:ByteArray):void
    {
        LOG.debug("parseBitmapData: {0}", stream);
        if (!loader)
        {
            loader = new Loader();
            loader.contentLoaderInfo.addEventListener(
                Event.COMPLETE,
                contentLoaderInfo_completeHandler
            );
            loader.contentLoaderInfo.addEventListener(
                IOErrorEvent.IO_ERROR,
                contentLoaderInfo_ioErrorHandler
            );
        }
        loader.loadBytes(stream);
    }

    /**
     *  @private
     *  Announce the resulting BitmapData to interested parties.
     */
    private function notifyResult(bitmapData:BitmapData):void
    {
        LOG.debug("notifyResult {0}", bitmapData);
        if (responder)
            responder.result(bitmapData);
    }

    /**
     *  @private
     */
    private function notifyFault(info:Object):void
    {
        if (responder)
            responder.fault(info);
    }

    //--------------------------------------------------------------------------
    //
    //  Event handlers
    //
    //--------------------------------------------------------------------------

    /**
     *  @private
     */
    private function urlLoader_completeHandler(event:Event):void
    {
        LOG.debug("urlLoader_completeHandler:  {0}", event);
        parseBitmapData(urlLoader.data)
    }

    /**
     *  @private
     */
    private function urlLoader_ioErrorEventHandler(event:IOErrorEvent):void
    {
        LOG.error("urlLoader_ioErrorEventHandler {0}", event);
        setBitmapData(null);
        setIsLoading(false);
        notifyFault(event);
    }

    /**
     *  @private
     */
    private function contentLoaderInfo_completeHandler(event:Event):void
    {
        LOG.debug("contentLoaderInfo_completeHandler: {0}", event);
        var bitmapData:BitmapData = Bitmap(loader.content).bitmapData;
        setBitmapData(bitmapData);
        notifyResult(bitmapData);
        setIsLoading(false);
    }

    /**
     *  @private
     */
    private function contentLoaderInfo_ioErrorHandler(event:IOErrorEvent):void
    {
        LOG.error("contentLoaderInfo_ioErrorHandler: {0}", event);
        setBitmapData(null);
        notifyFault(event);
        setIsLoading(false);
    }
}
}
